# -*- coding: utf-8 -*-
from db.mysql import MysqlClient
import requests
from itertools import product
from common.helper import Helper
from common.config import *
from urllib.parse import urlencode

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "超值短期全球自驾车意外伤害保险"
    # 生产产品数据
    def genProductInfo(self):
        plan = {
            "days":["7d","15d","30d","365d"],
            "people_count":["1"],
            "myselfDriver":["100000","200000","400000","500000"]
        }
        for v in product(plan["days"],plan["people_count"],plan["myselfDriver"]):
            data = Helper.formatProductInfo( plan,v )
            yield data
    #执行爬虫
    def requestJson(self):
        for v in self.genProductInfo():
            params = '''
            appName: 
            appSex: M
            appidType: A
            appidNo: 
            appBirthday: 1993-02-02
            appPhone: 
            appPro: 110000
            appCity: 110100
            appAddress: 
            appEmail: 
            name: 
            sex: M
            idType: A
            idNo: 
            birthday: 1993-02-02
            phone: 
            pro: 110000
            city: 110100
            address: 
            email: 
            source: CUS000000046
            planCode: P000000971
            planAmnt: 100000
            polTerm: 7
            poltermType: D
            payPeriod: 0
            payIntv: 0
            relation: 0
            '''
            data = Helper.perfectJson( params )
            data["planAmnt"] = v["myselfDriver"]
            data["polTerm"] = v["days"].replace("d","")
            payload = urlencode( data ).replace("+","")
            r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
            if r.status_code == 200 and "msg" in r.text:
                price = Helper.decimalParse( r.json()["msg"])
                data = {
                    "name":self.name,
                    "company":"大都会人寿",
                    "price":price
                }
                data.update( v )
                Helper.mergeTable(self.name,self.mysql,data )
